// pages/specific-goods/specific-goods.js

const SERVICE = require("../../service.js");

Page({

  /**
   * 页面的初始数据
   * @prama { Number }  showItem 导航和scroll-view的默认项
   * @prama { String }  SelectedEstimateItem 更多评论导航的默认项
   * @param { Number }  page   分页
   * @param { String || Number } id 商品id
   */
  data: {
    showItem: 0,
    showGoodsNum: false,
    SelectedEstimateItem: 0,
    page: 1,
    estimateNumber:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
    this.setData({
      id: options.id
    });
    
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this,td = this.data;

    specificGoods(_this, { id: td.id, openid: wx.getStorageSync("token") });

    wx.showNavigationBarLoading();
    // 获取不配送区域
    SERVICE.NDArea({ openid: wx.getStorageSync("token") }, (resStatus, data) => {
      wx.hideNavigationBarLoading();
      if (resStatus) {
        _this.setData({
          NDAreaData: data
        });
      }
    });

    // 获取用户评论
    SERVICE.UserEstimate({
      openid: wx.getStorageSync("token"),
      id: td.id,
      type: 1
    }, (resStatus, data) => {
      if (resStatus) {
        _this.setData({
          UserEstimateData: data
        });
      }
    });

    // 获取用户评论
    getUserEstimate(_this, {
      openid: wx.getStorageSync("token"),
      id: td.id,
      page: td.page,
      num: 15,
      type: td.SelectedEstimateItem + 1
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 
   *方法 
   * @Method: navItem 导航项
   * @Method: swiperChange 滑动页
   * @Method: collect 收藏
   * @Method: MoreEstimate 更多图片
   * @Method: preview 预览图片
   * @Methos: estimates 评论类型
   * @Methos: showMoreEstimate 显示更多评论
   */
  navItem(e) {
    let Item = e.currentTarget.dataset.index;
    this.setData({
      showItem: Item
    });
  },
  swiperChange(e) {
    let Item = e.detail.current;
    this.setData({
      showItem: Item
    });
  },
  MoreEstimate() {
    this.setData({
      showItem: 2
    });
  },
  collect(e) {
    let _this = this,
    td = this.data,
    collect_goodsId = e.currentTarget.dataset.id,
    collect_status = e.currentTarget.dataset.status,
    cancle_collect = e.currentTarget.dataset.collctid;
    
    if (collect_status == 0){
      wx.showLoading({
        title: "收藏中...",
      });
      SERVICE.collect({ openid: wx.getStorageSync("token"), id: collect_goodsId},(resStatus,data)=>{
        wx.hideLoading();
        if (resStatus){
          specificGoods(_this, { id: td.id, openid: wx.getStorageSync("token")});
          wx.showToast({
            title: "收藏成功",
            icon:"none",
            mask:true
          });
        }
      });
    } else if (collect_status == 1){
      wx.showLoading({
        title: "取消收藏中...",
      });
      SERVICE.cancelCollect({ openid: wx.getStorageSync("token"), id: cancle_collect }, (resStatus,data)=>{
        wx.hideLoading();
        if (resStatus) {
          specificGoods(_this, { id: td.id, openid: wx.getStorageSync("token") });
          wx.showToast({
            title: "取消收藏成功",
            icon: "none",
            mask: true
          });
        }
      });
    }
  },
  preview(e) {
    // 预览图片数据
    let preview_image = this.data.specificGoodsData.goods_desc;
    // 点击预览图片当前下标（项）
    let item = e.currentTarget.dataset.index;
    wx.previewImage({
      current: preview_image[item], // 当前显示图片的http链接
      urls: preview_image // 需要预览的图片http链接列表
    });
  },
  viewEstimageImgs(e){
    let preview_image = e.currentTarget.dataset.imgs;
    for (let i = 0; i < preview_image.length; i++){
      preview_image[i] = 'https://www.3160000.cn' + preview_image[i];
    }
    console.log("preview_image:", preview_image[0]);
    wx.previewImage({
      current: preview_image[0], // 当前显示图片的http链接
      urls: preview_image // 需要预览的图片http链接列表
    });
  },
  estimates(e) {
    let _this = this,
    td = this.data,
    SelectedEstimateItem = parseInt(e.currentTarget.dataset.index);
    
    this.setData({
      SelectedEstimateItem
    });
    if (td.UserEstimateData2){
      if (td.UserEstimateData2.number.all > 0) {
        getUserEstimate(_this, {
          openid: wx.getStorageSync("token"),
          id: td.id,
          page: td.page,
          num: 15,
          type: SelectedEstimateItem + 1
        });
      }
    }
  },
  showMoreEstimate() {
    let _this = this,
    td = this.data;
    getUserEstimate(_this, {
      openid: wx.getStorageSync("token"),
      id: td.id,
      page: ++td.page,
      num: 15,
      type: td.SelectedEstimateItem + 1
    });
  },
  addCart() {
    let _this = this,
      goods_id = _this.data.id,
      goods_data = _this.data.specificGoodsData;
    
    wx.showLoading({
      title: "加载中...",
    });
    
    // 获取规格
    SERVICE.getSpec({ id: goods_id }, (resStatus, data) => {
      wx.hideLoading();
      if (resStatus) {
        // 有规格时调用规格组件
        _this.setData({
          showSpec: data.list.length > 0 ? true : false,
          showSpecData: data,
          goods_id,
          specNum: 1,
          // showItem: 0,
          showSpceItem:0
        });
      } else {
        // 无规格时调用无规格组件
        _this.setData({
          showGoodsNum: true,
          goodsNumData: goods_data,
          goodsNum: 1,
          goods_id
        });
      }
    });
  },
  // 确定加入购物车（规格商品）
  confirmAddCart(e) {
    let _this = this,
      td = this.data,
      num = e.detail.num,
      spceId = e.detail.specId;

    SERVICE.addCart({
      number: num,
      spec: spceId,
      goods_id: td.goods_id,
      openid: wx.getStorageSync("token")
    }, (resStatus, data) => {
      console.log(data);
      specificGoods(_this, { id: td.id, openid: wx.getStorageSync("token") });      
      if (resStatus) {
        _this.setData({
          showSpec: false,
          showGoodsNum: false
        });
        // wx.showToast({
        //   title: data.message,
        //   duration: 1000,
        //   mask: true
        // });
        wx.showToast({
          title: "加入购物车成功！",
          duration: 1000,
          icon: "none",
          mask: true
        });
        setTimeout(() => {
          // 调用配件商品（有则显示，无则不显示）
          getGoodsMountings(e, data.goods_id);
        }, 1100);
      } else {
        wx.showToast({
          title: data.message,
          icon: "none",
          duration: 1000,
          mask: true
        });
      }
     
    });
  },
  submitRecommendGoods(e) {
    let _this = this, formData = e.detail.formData;
    let openid = wx.getStorageSync("token");
    if (formData.length > 0) {
      SERVICE.MultipleItemsAddCart({
        goods: JSON.stringify(formData), openid
      },
        (resStatus, data) => {
          console.log("配菜商品：", data);
          if (resStatus) {
            _this.setData({
              showRecommendGoods: false
            });
            wx.showToast({
              title: data.message,
              duration: 1000,
              mask: true
            });
          }
        });
    } else {
      wx.showToast({
        title: "请选择配菜",
        icon: "none",
        mask: true
      });
    }
  }
});

//获取具体商品
function specificGoods(e,params){
  SERVICE.getSpecificGoods(params, (resStatus, data) => {
    console.log("获取具体商品:",data);
    if (resStatus) {
      e.setData({
        specificGoodsData: data
      });
    }
  });
}

// 获取用户评论
function getUserEstimate(e, params){  
  let Type = {
    1:'all',
    2:'favorable',
    3:'medium',
    4:'bad',
    5:'image'
  };
  SERVICE.UserEstimate(params, (resStatus, data) => {
    console.log("用户评论：",data);
    if(resStatus) {
      if (data.list != null){
       e.setData({
         UserEstimateData2: data,
         estimateNumber: data.number[Type[params.type]]
       });
     }
    }
  });
}
// 获取商品配件
function getGoodsMountings(e, params) {
  SERVICE.getGoodsMountings(params, (resStatus, data) => {
    if (resStatus) {
      for (let i = 0; i < obj.length; i++) {
        obj[i].number = 1;
        obj[i].checked = false;
      }
      e.setData({
        showRecommendGoods: true,
        recommendGoodsData: obj
      });
    }
  });
}